/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import Enum.LoaiNguoiDungEnum;
import java.util.Date;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import pojo.ChiTietHoaDon;
import pojo.HoaDon;
import pojo.NguoiDung;
import pojo.SanPhamCuaHang;
import util.NewHibernateUtil;

/**
 *
 * @author 0
 */
public class HoaDonDAO extends BaseDAO {

    public static List<HoaDon> TimKiem(Integer maHoaDon, String tenKhachHang, Date ngayLapHoaDonFrom, Date ngayLapHoaDonTo, Integer idCuaHang, Integer idTrangThaiDonHang, NguoiDung nguoiDung) throws Exception {
        Session session = NewHibernateUtil.getSessionFactory().openSession();
        String string = "from HoaDon hd where (hd.isDelete=false or hd.isDelete=null)";
        if (nguoiDung.getLoaiNguoiDung().getId() != LoaiNguoiDungEnum.Admin.getCode()) {
            string += String.format(" and hd.cuaHang.id=%d", nguoiDung.getCuaHang().getId());
        }
        if (!tenKhachHang.isEmpty()) {
            string += " and lower(hd.nguoiDung.tenNguoiDung) like :tenKhachHang";
        }
        if (maHoaDon != null) {
            string += String.format(" and hd.id=%d", maHoaDon);
        }
        if (ngayLapHoaDonFrom != null) {
            string += " and hd.ngayLapHoaDon>=:ngayLapHoaDonFrom";
        }
        if (ngayLapHoaDonTo != null) {
            string += " and hd.ngayLapHoaDon<=:ngayLapHoaDonTo";
        }
        if (idCuaHang != null) {
            string += String.format(" and hd.cuaHang.id=%d", idCuaHang);
        }
        if (idTrangThaiDonHang != null) {
            string += String.format(" and hd.trangThaiDonHang.id=%d", idTrangThaiDonHang);
        }
        Query query = session.createQuery(string);
        if (!tenKhachHang.isEmpty()) {
            query.setString("tenKhachHang", "%" + tenKhachHang.toLowerCase() + "%");
        }
        if (ngayLapHoaDonFrom != null) {
            query.setDate("ngayLapHoaDonFrom", ngayLapHoaDonFrom);
        }
        if (ngayLapHoaDonTo != null) {
            query.setDate("ngayLapHoaDonTo", ngayLapHoaDonTo);
        }
        List<HoaDon> hoaDons = query.list();
        session.close();
        return hoaDons;
    }
    
    public static Integer Them(HoaDon hoaDon,List<ChiTietHoaDon> chiTietHoaDons) throws Exception{
        int id=0;
        Session session=NewHibernateUtil.getSessionFactory().openSession();
        Transaction transaction=session.beginTransaction();
        try{
            for(ChiTietHoaDon chiTietHoaDon:chiTietHoaDons){
                chiTietHoaDon.setHoaDon(hoaDon);
                SanPhamCuaHang sanPhamCuaHang=(SanPhamCuaHang) session.get(SanPhamCuaHang.class, chiTietHoaDon.getSanPhamCuaHang().getId());
                if(sanPhamCuaHang.getSoLuong()<chiTietHoaDon.getSoLuong()){
                    transaction.rollback();
                    session.close();
                    throw new Exception(String.format("Số lượng của sản phẩm %s chỉ còn %d cái, không thể đặt mua nhiều hơn số lượng này!",sanPhamCuaHang.getSanPham().getTenSanPham(),sanPhamCuaHang.getSoLuong()));
                }
                sanPhamCuaHang.setSoLuong(sanPhamCuaHang.getSoLuong()-chiTietHoaDon.getSoLuong());
                session.update(sanPhamCuaHang);
                session.save(chiTietHoaDon);
            }
            id = (int) session.save(hoaDon);
            transaction.commit();
            session.close();
        }
        catch(HibernateException exception){
            transaction.rollback();
            session.close();
            throw new Exception(exception.getMessage());
        }
        return id;
    }
    
    public static void Sua(HoaDon hoaDon,List<ChiTietHoaDon> chiTietHoaDons) throws Exception{
        Session session=NewHibernateUtil.getSessionFactory().openSession();
        Transaction transaction=session.beginTransaction();
        try{
            List<ChiTietHoaDon> cthds=session.createQuery(String.format("from ChiTietHoaDon cthd where cthd.hoaDon.id=%d",hoaDon.getId())).list();
            for(ChiTietHoaDon chiTietHoaDon:cthds){
                SanPhamCuaHang sanPhamCuaHang=(SanPhamCuaHang) session.get(SanPhamCuaHang.class, chiTietHoaDon.getSanPhamCuaHang().getId());
                sanPhamCuaHang.setSoLuong(sanPhamCuaHang.getSoLuong()+chiTietHoaDon.getSoLuong());
                session.delete(chiTietHoaDon);
                session.update(sanPhamCuaHang);
            }
            for(ChiTietHoaDon chiTietHoaDon:chiTietHoaDons){
                chiTietHoaDon.setHoaDon(hoaDon);
                SanPhamCuaHang sanPhamCuaHang=(SanPhamCuaHang) session.get(SanPhamCuaHang.class, chiTietHoaDon.getSanPhamCuaHang().getId());
                if(sanPhamCuaHang.getSoLuong()<chiTietHoaDon.getSoLuong()){
                    transaction.rollback();
                    session.close();
                    throw new Exception(String.format("Số lượng của sản phẩm %s chỉ còn %d cái, không thể đặt mua nhiều hơn số lượng này!",sanPhamCuaHang.getSanPham().getTenSanPham(),sanPhamCuaHang.getSoLuong()));
                }
                sanPhamCuaHang.setSoLuong(sanPhamCuaHang.getSoLuong()-chiTietHoaDon.getSoLuong());
                session.update(sanPhamCuaHang);
                session.save(chiTietHoaDon);
            }
            session.update(hoaDon);
            transaction.commit();
            session.close();
        }
        catch(HibernateException exception){
            transaction.rollback();
            session.close();
            throw new Exception(exception.getMessage());
        }
    }
    
    public static void HuyHoaDon(List<HoaDon> hoaDons) throws Exception{
        Session session=NewHibernateUtil.getSessionFactory().openSession();
        Transaction transaction=session.beginTransaction();
        try{
            for(HoaDon hoaDon:hoaDons){
                List<ChiTietHoaDon> chiTietHoaDons=session.createQuery(String.format("from ChiTietHoaDon cthd where cthd.hoaDon.id=%d",hoaDon.getId())).list();
                for(ChiTietHoaDon chiTietHoaDon:chiTietHoaDons){
                    SanPhamCuaHang sanPhamCuaHang=(SanPhamCuaHang) session.get(SanPhamCuaHang.class, chiTietHoaDon.getSanPhamCuaHang().getId());
                    sanPhamCuaHang.setSoLuong(sanPhamCuaHang.getSoLuong()+chiTietHoaDon.getSoLuong());
                    session.update(sanPhamCuaHang);
                }
                hoaDon.setIsDelete(true);
                session.update(hoaDon);
            }
            transaction.commit();
            session.close();
        }
        catch(HibernateException exception){
            transaction.rollback();
            session.close();
            throw new Exception(exception.getMessage());
        }
    }
    
    public static List<HoaDon> LayDanhSachBaoCaoHoaDon(Date ngayFrom, Date ngayTo, Integer idCuaHang) throws Exception{
        Session session=NewHibernateUtil.getSessionFactory().openSession();
        Query query=session.createQuery(String.format("from HoaDon hd where hd.cuaHang.id=%d and hd.ngayLapHoaDon>=:ngayFrom and hd.ngayLapHoaDon<=:ngayTo order by hd.id",idCuaHang));
        query.setDate("ngayFrom", ngayFrom);
        query.setDate("ngayTo", ngayTo);
        List<HoaDon> hoaDons=query.list();
        session.close();
        return hoaDons;
    }
}
